package com.util.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * @Description: 不规则带多表头写入
 * @Author: hechaobo
 * @Date: 2024/3/1
 **/
public class WriteLikeWord {
    ExcelWriter writer;
    Set<Integer> headLines=new HashSet<>();
    List<List> data=new LinkedList<>();
    public WriteLikeWord(String path){
        writer = EasyExcel.write(path).build();
    }
    public void addHead(List head){
        data.add(head);
        headLines.add(data.size()-1);
    }
    public void addData(List<List> d){
        data.addAll(d);
    }
    public void finish(){
        writer.write(data,EasyExcel.writerSheet().registerWriteHandler(new CellWriteHandler() {
            CellStyle cellStyle;

            @Override
            public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
                if(cellStyle==null){
                    cellStyle = writeSheetHolder.getSheet().getWorkbook().createCellStyle();
                    cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                    cellStyle.setFillForegroundColor((IndexedColors.YELLOW.index));
                    cellStyle.setBorderBottom(BorderStyle.THIN);
                    cellStyle.setBorderLeft(BorderStyle.THIN);
                    cellStyle.setBorderRight(BorderStyle.THIN);
                    cellStyle.setBorderTop(BorderStyle.THIN);
                }
                if(headLines.contains(relativeRowIndex)){
                    cell.setCellStyle(cellStyle);
                }
            }
        }).build());
        writer.finish();
    }
}
